package com.cn.wanxi.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class IOTool {

    private IOTool() {
    }

    /**
     * 创建文件
     *
     * @param path      路径
     * @param directory 文件夹
     * @param fileName  文件名
     * @return 返回文件
     */
    public static File createFile(String path, String directory, String fileName) {
        File tempDirectory = new File(path, directory);
        tempDirectory.mkdir();//创建文件夹
        File file = new File(tempDirectory, fileName);
        try {
            file.createNewFile();//創建文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static void writeData(File file, List<String> data) {
        try {
            OutputStream outputStream = new FileOutputStream(file);
            for (int i = 0; i < data.size(); i++) {
                outputStream.write(data.get(i).getBytes(StandardCharsets.UTF_8));
                outputStream.write(Path.SPILT.getBytes(StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件里面的数据
     *
     * @param file
     */
    public static String readData(File file) {
        StringBuilder result = new StringBuilder();
        try {
            InputStream inputStream = new FileInputStream(file);
            Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
//            Reader reader = new FileReader(file);

            int read;
            while ((read = reader.read()) != -1) {
                result.append((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
